<template>
    <section class="common-upload-container clear" :class="{'upload-single-container':modelType == 'string'}">
        <ul class="el-upload-list" v-if="modelType == 'array' || modelType == 'string' && readonly">
            <li
                v-for="(item,index) in modelType == 'array' ? uploadForm[modelProp] : [uploadForm[modelProp]]"
                :key="index"
                class="el-upload-list__item"
                @click="showImageViewHandle(index)">
                <img v-lazy="item.url" alt="">
                <van-icon
                    v-if="!readonly"
                    name="cross"
                    @click.stop="deleteImageHandle(index)" />
            </li>
        </ul>
        <van-uploader
            v-if="!readonly"
            name="uploader"
            accept="image/*"
            :disabled="readonly"
            :multiple="multiple"
            :before-read="beforeReadHandle"
            :after-read="afterReadHandle">
                <img :src="uploadForm[modelProp]" alt="" v-if="modelType == 'string' && uploadForm[modelProp]">
                <van-icon name="photograph" v-else/>
        </van-uploader>
    </section>
</template>

<script>
    import { ImagePreview } from 'vant';
    import {uploadfile} from '@/utils/getData';

    export default {
        name: "v-upload",
        props:{
            uploadForm: {  // 绑定的表单
                required: true
            },
            modelProp:{
                required:true,
            },
            readonly: {   // 是否可编辑
                default: false
            },
            multiple:{//是否多选
                default: true
            },
            modelType:{
                default:'array',//string
            }
        },
        data(){
            return{
            }
        },
        methods:{
            beforeReadHandle(file){//上传前
                try{
                    if(Object.prototype.toString.call(file) === '[object Array]' && file.length > 0){
                        file.forEach(item=>{
                            const isLt2M = item.size / 1024 / 1024 < 39;
                            if (!isLt2M) {
                                throw {message:item.name+'文件大小不能超过39M！'}
                            }
                        });
                        return true;
                    }else{
                        const isLt2M = file.size / 1024 / 1024 < 39;
                        if (!isLt2M) {
                            this.$toast({
                                message:'文件大小不能超过39MB!',
                                forbidClick:false
                            });
                            return false;
                        }
                        return isLt2M;
                    }
                }catch (e) {
                    this.$toast({
                        message:e.message,
                        forbidClick:false
                    });
                }
            },
            compressHandle(file){//图片压缩
                try{
                    return new Promise((resolve,reject)=>{
                        if(file.file.size > 200*1024){//小于200kb则不压缩
                            let fileContent = '';
                            // 创建Canvas对象(画布)
                            let canvas =  document.createElement('canvas');
                            // 获取对应的CanvasRenderingContext2D对象(画笔)
                            let context = canvas.getContext('2d');
                            // 创建新的图片对象
                            let img = new Image();
                            // 指定图片的DataURL(图片的base64编码数据)
                            img.src = file.content;
                            // 监听浏览器加载图片完成，然后进行进行绘制
                            img.onload = () => {
                                // 指定canvas画布大小，该大小为最后生成图片的大小
                                canvas.width = img.width;
                                canvas.height = img.height;
                                /* drawImage画布绘制的方法。(0,0)表示以Canvas画布左上角为起点，400，300是将图片按给定的像素进行缩小。
                                如果不指定缩小的像素图片将以图片原始大小进行绘制，图片像素如果大于画布将会从左上角开始按画布大小部分绘制图片，最后的图片就是张局部图。*/
                                context.drawImage(img, 0, 0, img.width, img.height);
                                // 将绘制完成的图片重新转化为base64编码，file.file.type为图片类型，0.92为默认压缩质量
                                fileContent = canvas.toDataURL(file.file.type, 0.92);
                                resolve(fileContent);
                            };
                            // img.onerror = ()=>{
                            //     reject();
                            // }
                        }else{
                            resolve(file.content);
                        }
                    });
                }catch (e) {
                    this.$toast({
                        message:e.message,
                        forbidClick:false
                    });
                }
            },
            afterReadHandle(file){//上传后
                try{
                    const that = this;
                    let baseImages = [];
                    if(Object.prototype.toString.call(file) === '[object Array]' && file.length > 0){
                        baseImages = JSON.parse(JSON.stringify(file));
                    }else{
                        baseImages.push(file);
                    }
                    baseImages.forEach(async (baseImage)=>{
                        try{
                            let item = await that.compressHandle(baseImage);
                            const res = await uploadfile({'mypic':item});
                            if(res.error){
                                throw {message:res.error};
                            }
                            if(that.modelType == 'string'){
                                that.$set(that.uploadForm,that.modelProp,res.success);
                            }else{
                                that.uploadForm[that.modelProp] = that.uploadForm[that.modelProp].concat(res.success);
                            }
                            console.log(that.uploadForm);
                        }catch (e) {
                            this.$toast({
                                message:e.message,
                                forbidClick:false
                            });
                        }
                    });
                }catch (e) {
                    this.$toast({
                        message:e.message,
                        forbidClick:false
                    });
                }
            },
            deleteImageHandle(index){//删除
                const that = this;
                this.$dialog.confirm({
                    message: '确定删除吗？',
                }).then(async ()=>{
                    try{
                        if(that.modelType == 'string'){
                            that.uploadForm[that.modelProp] = '';
                        }else{
                            that.uploadForm[that.modelProp].splice(index,1);
                        }
                    }catch (e) {
                        this.$toast({
                            message:e.message,
                            forbidClick:false
                        });
                    }
                }).catch(()=>{
                    return false;
                });
            },
            showImageViewHandle(index){//查看图片
                try {
                    let imagesArr = [];
                    let imageLists = this.modelType == 'array' ? this.uploadForm[this.modelProp] : [this.uploadForm[this.modelProp]];
                    imageLists.forEach(item=>{
                        imagesArr.push(item.url)
                    })
                    ImagePreview({
                        images: imagesArr,
                        startPosition: index,
                        onClose() {
                            // do something
                        }
                    });
                }catch (e) {
                    this.$toast({
                        message:e.message,
                        forbidClick:false
                    });
                }
            }
        }
    }
</script>

<style scoped>
    .common-upload-container{
        padding: 10px 10px;
    }
    .upload-single-container{
        padding: 0;
        width: 100%;
        height: 100%;
    }
    .el-upload-list{
        margin: 0;
        display: inline;
        vertical-align: top;
    }
    .el-upload-list__item{
        width: 80px;
        height: 80px;
        line-height: 80px;
        margin: 0 15px 8px 0;
        position: relative;
        float: left;
        background-color: #fff;
        border: 1px solid #c0ccda;
        cursor: pointer;
    }
    .van-uploader{
        width: 80px;
        height: 80px;
        text-align: center;
        border: 1px dashed #c0ccda;
        float: left;
        display:flex;
        justify-content:center;
        align-items: center;
    }
    .upload-single-container .van-uploader{
        width: 100%;
        height: 100%;
        border: none;
    }
    .van-icon-photograph{
        font-size: 22px;
    }
    .van-icon-cross{
        position: absolute;
        right:0px;
        top:0px;
        font-size: 12px;
        width: 19px;
        height: 19px;
		line-height:19px;
        text-align: center;
		background:#ff0000;
		color:#fff;
    }
</style>